﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Eassets.Layered.Domain;
using Eassets.UI.Components;


namespace OpenArc.Erims.Web.Components
{
    public partial class TreeBrowser : System.Web.UI.UserControl
    {

        public string Caption
        {
            set
            {
                labelTreeBrowserCaption.Text = value;
            }
        }

        public string BrowserObject { get; set; }

        public string[] FilterOptions { get; set; }

        private Boolean IsBrowserVisible
        {
            get
            {
                if (ViewState["TreeBrowserVisible"] == null)
                {
                    ViewState["TreeBrowserVisible"] = false;
                }
                return Convert.ToBoolean(ViewState["TreeBrowserVisible"]);
            }
            set { ViewState["TreeBrowserVisible"] = value; }
        }

        public string SelectedRecordValues
        {
            get { return this.hiddenFieldSelectedRecord.Value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack && IsBrowserVisible)
            {
                mpeTreeBrowser.Show();
            }        
        }


        //private void LoadOrganizationStructureGroupOfCompaniesTree()
        //{
        //    treeViewBrowser.Nodes.Clear();

        //    TreeNode newNode = new TreeNode("Org. Structure", 0.ToString());

        //    OrganizationStructureService organizationStructureService = new OrganizationStructureService();
        //    Collection<OrganizationStructure> organizationStructures =
        //        organizationStructureService.
        //            GetOrganizationStructuresOfCurrentGroupOfCompaniesByCurrentCompanyOrgStructureId(
        //            Convert.ToInt64(Session[Global.KeyCurrentCompanyId]));
            
        //    FillOrganizationStructureTree(organizationStructures, newNode);
        //}

        //private void LoadOrganizationStructureTree()
        //{
        //    treeViewBrowser.Nodes.Clear();

        //    TreeNode newNode = new TreeNode("Org. Structure", 0.ToString());

        //    OrganizationStructureService organizationStructureService = new OrganizationStructureService();
        //    //Collection<OrganizationStructure> organizationStructures = organizationStructureService.GetAllorganizationStructures();
        //    Collection<OrganizationStructure> organizationStructures =
        //        organizationStructureService.GetOrganizationStructuresByMainCompanyOrgStructure(
        //                Convert.ToInt64(Session[Global.KeyCurrentCompanyStakeholderId]));
        //    //                    Convert.ToInt64(Session[Global.KeyCurrentCompanyId]));
        //    FillOrganizationStructureTree(organizationStructures, newNode);
        //}

        /// <summary>
        /// Fills the organization structure tree.
        /// Populate the Tree 
        /// The parent serial is submitted as the parameter to filter the object collection
        /// The child nodes of the parent serial will be filtered 
        /// and again the function will be called to fill the child nodes of each of those nodes
        /// This function behaves as a recursive function
        /// </summary>
        /// <param name="sourceCollection">The source collection.</param>
        /// <param name="parentTreeNode">The parent tree node.</param>
        //private void FillOrganizationStructureTree(Collection<Domain.Ecorp.OrganizationStructure> sourceCollection, TreeNode parentTreeNode)
        //{
        //    // Get all children of the current parent
        //    Collection<Domain.Ecorp.OrganizationStructure> o =
        //        new Collection<Domain.Ecorp.OrganizationStructure>(
        //        sourceCollection.Where(
        //            x =>
        //            parentTreeNode.Value == 0.ToString()
        //                ? x.ParentOrganizationStructure == null
        //                : (x.ParentOrganizationStructure != null) && (x.ParentOrganizationStructure.OrganizationStructureId.ToString() == parentTreeNode.Value)).ToList());

        //    foreach (Domain.Ecorp.OrganizationStructure orig in o)
        //    {
        //        TreeNode newNode =
        //            new TreeNode(orig.Businessunitlist.description, orig.OrganizationStructureId.ToString());
        //        if (parentTreeNode == null)
        //        {
        //            treeViewBrowser.Nodes.Add(newNode);
        //        }
        //        else if (parentTreeNode.Value == 0.ToString())
        //        {
        //            treeViewBrowser.Nodes.Add(newNode);
        //        }
        //        else
        //        {
        //            parentTreeNode.ChildNodes.Add(newNode);
        //        }
        //        FillOrganizationStructureTree(sourceCollection, newNode);
        //    }
        //}

        //private void LoadBusinessSectors()
        //{
        //    treeViewBrowser.Nodes.Clear();

        //    TreeNode newNode = new TreeNode("Business Sectors", 0.ToString());

        //    BusinessSectorService businessSectorService = new BusinessSectorService();
        //    Collection<BusinessSector> businessSectors = businessSectorService.GetAllBusinessSectors();
        //    FillBusinessSectorsTree(businessSectors, newNode);
        //}

        // Populate the Tree 
        // The parent serial is submitted as the parameter to filter the object collection
        // The child nodes of the parent serial will be filtered 
        // and again the function will be called to fill the child nodes of each of those nodes
        // This function behaves as a recursive function
        //private void FillBusinessSectorsTree(Collection<BusinessSector> sourceCollection, TreeNode parentTreeNode)
        //{
        //    // Get all children of the current parent
        //    Collection<BusinessSector> o = new Collection<BusinessSector>(
        //        sourceCollection.Where(
        //            x =>
        //            parentTreeNode.Value == 0.ToString()
        //                ? (x.ParentBusinessSector == null) || (x.ParentBusinessSector.BusinessSectorId == 0)
        //                : (x.ParentBusinessSector != null) && (x.ParentBusinessSector.BusinessSectorId.ToString() == parentTreeNode.Value)).ToList());

        //    foreach (BusinessSector orig in o)
        //    {
        //        TreeNode newNode = new TreeNode(orig.Description, orig.BusinessSectorId.ToString());

        //        //parentTreeNode.ChildNodes.Add(newNode);
        //        if (parentTreeNode == null)
        //        {
        //            treeViewBrowser.Nodes.Add(newNode);
        //        }
        //        else if (parentTreeNode.Value == 0.ToString())
        //        {
        //            treeViewBrowser.Nodes.Add(newNode);
        //        }
        //        else
        //        {
        //            parentTreeNode.ChildNodes.Add(newNode);
        //        }
        //        FillBusinessSectorsTree(sourceCollection, newNode);
        //    }
        //}

        //private void LoadPositionHierarchyByBusinessUnit()
        //{
        //    treeViewBrowser.Nodes.Clear();

        //    TreeNode newNode = new TreeNode("Position Structure", "0");
        //    treeViewBrowser.Nodes.Add(newNode);

        //    if (FilterOptions.Length > 0)
        //    {
        //        CompanyPositionStructureService companyPositionStructureService = new CompanyPositionStructureService();
        //        Collection<CompanyPositionStructure> companyPositionStructures =
        //            companyPositionStructureService.GetCompanyPositionsByBusinessUnitListId(
        //                Convert.ToInt64(FilterOptions[1]));

        //        Collection<long> positionHierarchyIds = new Collection<long>();
        //        foreach (CompanyPositionStructure structure in companyPositionStructures)
        //        {
        //            positionHierarchyIds.Add(structure.PositionHierarchy.PositionHierarchyId);
        //        }
        //        ViewState["ApplicablePositions"] = positionHierarchyIds;

        //        FillPositionHierarchy(companyPositionStructures, newNode);
        //    }

        //    treeViewBrowser.Nodes[0].Expand();
        //}

        // Populate the Tree 
        // The parent serial is submitted as the parameter to filter the object collection
        // The child nodes of the parent serial will be filtered 
        // and again the function will be called to fill the child nodes of each of those nodes
        // This function behaves as a recursive function
        //private void FillPositionHierarchy(Collection<CompanyPositionStructure> sourceCollection, TreeNode parentTreeNode)
        //{
        //    // Get all children of the current parent
        //    //Collection<CompanyPositionStructure> o = new Collection<CompanyPositionStructure>(
        //    //    sourceCollection.Where(
        //    //        x =>
        //    //        parentTreeNode.Value == 0.ToString()
        //    //            ? (x.OrganizationStructure.OrganizationStructureId == Convert.ToInt64(FilterOptions[0]))
        //    //            : (x.PositionHierarchy.ParentPositionHierarchy != null) &&
        //    //              (x.PositionHierarchy.ParentPositionHierarchy.PositionHierarchyId.ToString() ==
        //    //               parentTreeNode.Value)).ToList());

        //    Collection<CompanyPositionStructure> o = new Collection<CompanyPositionStructure>(
        //        sourceCollection.Where(
        //            x =>
        //            parentTreeNode.Value == 0.ToString()
        //                ? (x.OrganizationStructure.OrganizationStructureId == Convert.ToInt64(FilterOptions[0]))
        //                : (x.PositionHierarchy.ParentPositionHierarchy != null) &&
        //                  (x.PositionHierarchy.ParentPositionHierarchy.PositionHierarchyId.ToString() ==
        //                   sourceCollection.Where(
        //                       y => y.CompanyPositionStructureId == Convert.ToInt64(parentTreeNode.Value)).
        //                       FirstOrDefault().PositionHierarchy.PositionHierarchyId.ToString())).ToList());

        //    foreach (CompanyPositionStructure orig in o)
        //    {
        //        if (parentTreeNode.Value == "0")
        //        {
        //            if (!((Collection<long>)ViewState["ApplicablePositions"]).Contains(orig.PositionHierarchy.ParentPositionHierarchy.PositionHierarchyId))
        //            {
        //                TreeNode newNode = new TreeNode(orig.PositionHierarchy.LeadershipPosition.Description,
        //                                            orig.CompanyPositionStructureId.ToString());

        //                parentTreeNode.ChildNodes.Add(newNode);
        //                FillPositionHierarchy(sourceCollection, newNode);
        //            }
        //        }
        //        else
        //        {
        //            TreeNode newNode = new TreeNode(orig.PositionHierarchy.LeadershipPosition.Description,
        //                                        orig.CompanyPositionStructureId.ToString());

        //            parentTreeNode.ChildNodes.Add(newNode);
        //            FillPositionHierarchy(sourceCollection, newNode);
        //        }
        //    }
        //}

        protected void treeViewBrowser_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = this.treeViewBrowser.SelectedNode;
            this.hiddenFieldSelectedRecord.Value = selectedNode.Value + "|" + selectedNode.Text;
        }

        public delegate void StakeholderBrowser_OkClick(object sender, EventArgs e);
        public event StakeholderBrowser_OkClick OkClick;
        protected void buttonOk_Click(object sender, EventArgs e)
        {
            OkClick(sender, e);
        }

        protected void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        public void Show()
        {
            IsBrowserVisible = true;

            if (BrowserObject == "OrganizationStructure")
            {
                if (String.IsNullOrEmpty(labelTreeBrowserCaption.Text) || labelTreeBrowserCaption.Text == "Tree Browser")
                {
                    labelTreeBrowserCaption.Text = "Org. Structure";
                }
                //LoadOrganizationStructureTree();
            }
            else if (BrowserObject == "OrgStructureForGroupOfCompanies")
            {
                if (String.IsNullOrEmpty(labelTreeBrowserCaption.Text) || labelTreeBrowserCaption.Text == "Tree Browser")
                {
                    labelTreeBrowserCaption.Text = "Org. Structure";
                }
              //  LoadOrganizationStructureGroupOfCompaniesTree();
            }
            else if (BrowserObject == "ChartOfAcc")
            {
                if (String.IsNullOrEmpty(labelTreeBrowserCaption.Text) || labelTreeBrowserCaption.Text == "Tree Browser")
                {
                    labelTreeBrowserCaption.Text = "Chart of Accounts";
                }
               // LoadChartOfAccounts();
            }
            else if (BrowserObject == "ChartOfAccForTran")
            {
                if (String.IsNullOrEmpty(labelTreeBrowserCaption.Text) || labelTreeBrowserCaption.Text == "Tree Browser")
                {
                    labelTreeBrowserCaption.Text = "Chart of Accounts";
                }
              //  LoadChartOfAccountsForTransactions();
            }
            else if (BrowserObject == "BusinessSector")
            {
                if (String.IsNullOrEmpty(labelTreeBrowserCaption.Text) || labelTreeBrowserCaption.Text == "Tree Browser")
                {
                    labelTreeBrowserCaption.Text = "Business Sectors";
                }
              //  LoadBusinessSectors();
            }
            else if (BrowserObject == "Sub Category")
            {
                if (String.IsNullOrEmpty(labelTreeBrowserCaption.Text) || labelTreeBrowserCaption.Text == "Tree Browser")
                {
                    labelTreeBrowserCaption.Text = "Sub Category";
                }
                //LoadSubCategory();
            }

            mpeTreeBrowser.Show();
        }
        ////private void LoadSubCategory()
        ////{
        ////    treeViewBrowser.Nodes.Clear();

        ////    TreeNode newNode = new TreeNode("Sub Category", 0.ToString());


        ////    AssetCategoryService productCategoryService = new AssetCategoryService();
        ////    Collection<Category> SubProductCategorys = new Collection<Category>();

        ////    SubProductCategorys =
        ////        productCategoryService.GetProductSubCategoryById(Convert.ToInt64(Session[GlobalData.KeyProductSubCategoryId]));


        ////    FillSubProductCategoriesTree(SubProductCategorys, newNode);
        ////}
        ////private void FillSubProductCategoriesTree(Collection<Domain.Reference.ProductCategoryDomain> sourceCollection, TreeNode parentTreeNode)
        ////{


        ////    Collection<ProductCategoryDomain> o = new Collection<ProductCategoryDomain>(
        ////        sourceCollection.Where(
        ////            x =>
        ////            parentTreeNode.Value == 0.ToString()
        ////                ? (x.ProductCategoryParentId == null || x.ProductCategoryParentId == 0)
        ////                : (x.ProductCategoryParentId != null) && (x.ProductCategoryParentId.ToString() == parentTreeNode.Value)).ToList());

        ////    foreach (ProductCategoryDomain orig in o)
        ////    {
        ////        TreeNode newNode = new TreeNode(orig.Code, orig.ProductCategoryId.ToString());
        ////        if (parentTreeNode == null)
        ////        {
        ////            treeViewBrowser.Nodes.Add(newNode);
        ////        }
        ////        else if (parentTreeNode.Value == 0.ToString())
        ////        {
        ////            treeViewBrowser.Nodes.Add(newNode);
        ////        }
        ////        else
        ////        {
        ////            parentTreeNode.ChildNodes.Add(newNode);
        ////        }

        ////        FillSubProductCategoriesTree(sourceCollection, newNode);

        ////    }


        ////}

        public void Hide()
        {
            IsBrowserVisible = false;
            mpeTreeBrowser.Hide();
        }
    }
}